package com.fcscs.cservice.dao.hibernate;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.fcscs.core.dao.ConnectionManager;
import com.fcscs.core.domain.BaseEntity.DBLoc;
import com.fcscs.cservice.dao.InRoomItemDao;
import com.fcscs.cservice.domain.InRoomItem;

@SuppressWarnings("unchecked")
@Repository("inRoomItemDao")
public class InRoomItemDaoHibernate extends BaseDaoHibernate<InRoomItem> implements InRoomItemDao {

	private static DBLoc DBLoc = new InRoomItem().getDBLoc();

	@Autowired
	private ConnectionManager connMgr;
	
	private static final String NAME_CNT = "select count(*) from in_room_item where org_id = :orgId and "
			+ " property_id = :propId and name = :name and id <> :id and active = true ";
	
	private static final String FIND = " from InRoomItem where orgId = :orgId and propertyId = :propId ";

	@Override
	protected Class<InRoomItem> getCls() {
		return InRoomItem.class;
	}

	@Override
	protected ConnectionManager getConnectionManager() {
		return connMgr;
	}

	@Override
	protected DBLoc getDBLoc() {
		return DBLoc;
	}

	@Override
	public <E extends InRoomItem> E get(Class<E> cls, long id) {
		return (E) getConnectionManager().getCurrentSession(getDBLoc()).load(cls, id);
	}

	@Override
	public <E extends InRoomItem> void save(E loc) {
		getConnectionManager().getCurrentSession(DBLoc).saveOrUpdate(loc);
	}

	@Override
	public boolean isInRoomItemTaken(long orgId, long propId, String name, Long id, long versionId) {
		Query q = connMgr.getCurrentSession(getDBLoc()).createSQLQuery(NAME_CNT);
		q.setString("name", name);
		q.setLong("id", id == null ? -1 : id);
		q.setLong("orgId", orgId);
		q.setParameter("propId", propId, Hibernate.LONG);
		return ((Number) q.uniqueResult()).intValue() > 0;
	}

	@Override
	public List<InRoomItem> getInRoomItemList(long orgId, long propId, boolean isCurrent) {
		Query q = connMgr.getCurrentSession(DBLoc).createQuery(FIND);
		q.setLong("orgId", orgId);
		q.setParameter("propId", propId, Hibernate.LONG);
		return q.list();
	}

	@Override
	public List<InRoomItem> getInRoomItemList(long orgId, long propId, long versionId) {
		Query q = connMgr.getCurrentSession(DBLoc).createQuery(FIND);
		q.setLong("orgId", orgId);
		q.setParameter("propId", propId, Hibernate.LONG);
		return q.list();
	}

}
